package com.singing.manager;

import com.singing.dao.AdminDao;
import com.singing.model.Admin;
import com.singing.model.Command;
import com.singing.util.AdminContext;

import java.util.List;
import java.util.Scanner;

public class AdminLoginManager extends BaseManager {


    // 输入管理员登陆信息
    private static final int INPUT_USERNAME_PASSWORD = 1;
    AdminDao adminDao = new AdminDao();

    public AdminLoginManager(String title, List<Command> commandList) {
        super(title, commandList);
    }

    @Override
    protected int processCommand(int command) {
        if (command == INPUT_USERNAME_PASSWORD) {
            Scanner scanner = new Scanner(System.in);

            main:
            while (true) {
                System.out.println("请输入账号");
                String account = scanner.next();
                System.out.println("请输入密码：");
                String password = scanner.next();

                if (!login(account, password)) {
                    while (true) {
                        System.err.println("账号或密码错误,1、重新输入 2、返回登陆页面");
                        int result = scanner.nextInt();
                        if (result == 1) {
                            continue main;
                        } else if (result == 2) {
                            break main;
                        } else {
                            System.err.println("输入错误，请重新输入");
                        }
                    }
                } else {
                    System.out.println("登录成功");
                    break;
                }
            }
        }
        return LOGIN_SUCCESS;
    }


    private boolean login(String username, String password) {
        Admin admin = adminDao.selectByAccount(username);

        if (admin == null) {
            return false;
        }
        if (!admin.getPassword().equals(password)) {
            return false;
        }

        AdminContext.setAdmin(admin);
        return true;
    }
}
